<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
  <style>
    #app {
      width: 600px;
      height: 400px;
      contain: strict;
      border: 1px solid red;
      contain: strict;
      overflow-anchor: none;
      overflow-y: auto;
      content-visibility: auto;
      contain-intrinsic-size: 300px;
      scroll-behavior: smooth;


    }
  </style>
</head>

<body>
  <div id="app"></div>
  <br />
  <button>插入</button>


  <script type="module">
    // requestIdleCallback  Safari不支持
    const requestIdleCallback = window.requestIdleCallback ||
      function (cb) {
        return setTimeout(() => {
          cb({
            timeRemaining: () => 16, // 模拟 16ms 的空闲时间
            didTimeout: false
          });
        }, 0);
      };

    const cancelIdleCallback = window.cancelIdleCallback ||
      function (id) {
        clearTimeout(id);
      };




    const list = new Array(100_000).fill(0)
    const app = document.getElementById('app')
    const btn = document.querySelector('button')
    btn.addEventListener('click', () => {
      requestIdleCallback(handle, { timeout: 1000 })
    })

    const fragment = document.createDocumentFragment();
    let taskIndex = 0
    function handle(deadline) {
      // 创建一个文档片段
      const fragment = document.createDocumentFragment();
      while (deadline.timeRemaining() > 0 && taskIndex < list.length) {
        const div = document.createElement('div')
        div.textContent = taskIndex + 1
        // 将元素添加到文档片段中
        fragment.appendChild(div);
        taskIndex++
      }
      // 将文档片段一次性插入到 DOM 中
      app.appendChild(fragment);

      if (taskIndex < list.length) {
        requestIdleCallback(handle)
      } else {
        console.log('任务执行完毕')
        taskIndex = 0
        return
      }
    }

  </script>
</body>

</html>